package projectmanagement.managementtool.ProjectServices;

import java.util.*;

import projectmanagement.managementtool.IdGenerator;
import projectmanagement.models.Iteration;
import projectmanagement.models.Project;
import projectmanagement.models.Task;

public class ProjectServiceImpl implements ProjectService {

    private Map<Integer, Project> mapOfProjects = new HashMap<Integer, Project>();

    public void setMapOfProjects(Map<Integer, Project> mapOfProjects) {
        this.mapOfProjects = mapOfProjects;
    }

    public int getIdByProjectName(String name) {
        for(Project prj : mapOfProjects.values()){
            if(name.equals(prj.getProjectName()))
                return prj.getProjectId();
        }
        return -1;
    }

    public boolean isProjectNameValid(String name) {
        for(Project prj : mapOfProjects.values())
            if(prj.getProjectName().equals(name))
                return false;
        return true;
    }

    public Project getProjectByName(String name) {
        Project project = null;
        for(Project prj : mapOfProjects.values())
            if(name.equals(prj.getProjectName()))
                return project = prj;

        return project;
    }

    public List<Iteration> listOfIterations = new ArrayList<Iteration>();
	
    public Project createProject(String projectName, Calendar projectStartDate, Calendar projectFinishDate, String projectDescription) {
		Project project = new Project(projectName, projectStartDate, projectFinishDate, projectDescription);
		int projectId = IdGenerator.generate(Project.class);
		project.setProjectId(projectId);
		mapOfProjects.put(projectId, project);

		return project;
	}
	
	public Project updateProject(Project project) {
		project = mapOfProjects.get(project.getProjectId());
		mapOfProjects.put(project.getProjectId(), project);
		return project;
	}

	public void deleteProject(Project project) {
		mapOfProjects.remove(project.getProjectId());
	}

    @Override
    public boolean addTask(int projectId, Task task) {
        Project project = getProjectById(projectId);
        if (project == null)
            return false;
        return project.addTask(task);
    }

    public Collection<Project> showListOfProjects() {
		return mapOfProjects.values();
    }

	public Collection<Iteration> showListOfProjectIterations() {
		return listOfIterations;
	}

    public Project getProjectById(int projectId) {
        for(Project p : mapOfProjects.values()) {
            if (p.getProjectId() == projectId)
                return p;
        }
        return null;
    }
}